/*左侧导航*/
import React, { Component } from 'react';
import { Layout, Menu, Icon } from 'antd';
import {Link, withRouter} from 'react-router-dom';
import {connect} from 'react-redux';
import {actionCreators} from './store';
import {Session} from "../../util";
import menuConfig from '../../configs/left_menu_configs';
import './style.less';

const { Sider } = Layout;
const { SubMenu, Item } = Menu;

class LeftMenu extends Component {
  constructor(props) {
    super(props);
    this.state = {
      collapsed: true,  // 控制菜单展开或收起
      currentKey: ''  // 当前选中的目录
    };
    this.onCollapse = this.onCollapse.bind(this);
    this.createMenu = this.createMenu.bind(this);
  }

  render() {
    const { collapsed, currentKey } = this.state;
    return (
      <Sider
        className="pinlor-sub-menu-box"
        collapsible
        collapsed={collapsed}
        onCollapse={this.onCollapse}
      >
        <Menu
          theme="dark"
          selectedKeys={[currentKey]}
          mode="inline" className="pinlor-sub-menu">
          {menuConfig ? this.createMenu(menuConfig): null}
        </Menu>
      </Sider>
    )
  }

  componentDidMount(){
    const currentKey = this.props.location.pathname;
    const menuArr = Session.getKey('menuArr') || [];
    this.props.setMenu(menuArr);   // 设置面包屑导航的位置
    this.setState({
      currentKey
    })
  }

  onCollapse() {
    this.setState(prevState => ({
      collapsed: !prevState.collapsed
    }));
  }

  handleClick = ({item, key})=>{
    const {title} = item.props;
    const parentTitle = item.props['parent-title'];
    let menuArr = [parentTitle, title];
    Session.setKey('menuArr', menuArr);
    this.props.setMenu(menuArr);   // 设置面包屑导航的位置
    this.setState({
      currentKey: key
    })
  };

  createMenu(config, parentTitle) {
    return config.map(item => {
      const { key, title, children, icon } = item;
      if (children) {
        // 有下一级菜单的情况
        return (
          <SubMenu
            key={key}
            title={<span><Icon type={icon} /><span>{title}</span></span>}
          >
            {
              this.createMenu(children, title)
            }
          </SubMenu>
        )
      }
      // 没有下一级菜单的情况
      return (
        <Item key={key} title={title} parent-title={parentTitle} onClick={this.handleClick}>
          <Link to={key}>
            {icon ? <Icon type={icon} /> : null}
            <span>{title}</span>
          </Link>
        </Item>
      );
    })
  }
}

const mapStateToDispatch = dispatch => ({
  setMenu(name){
    dispatch(actionCreators.setMenuName(name))
  }
});

export default withRouter(connect(null, mapStateToDispatch)(LeftMenu));
